package api

import (
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"github.com/kataras/iris/context"
	"github.com/ngaut/log"
	"global/function"
	"server/bitkop/app/common"
	"server/bitkop/core"
)

var selectTypes = map[string]string{
	"1week":  "1w",
	"3day":   "3d",
	"1day":   "1d",
	"12hour": "12h",
	"6hour":  "6h",
	"4hour":  "4h",
	"2hour":  "2h",
	"1hour":  "1h",
	"30min":  "30m",
	"15min":  "15m",
	"5min":   "5m",
	"3min":   "3m",
	"1min":   "1m",
}

type ResultItem [6]interface{}

func TrustKline(ctx context.Context) {

	// TODO 调试允许跨域
	ctx.Header("Access-Control-Allow-Origin", "*")
	ctx.Header("Access-Control-Allow-Headers", "Content-Type")
	ctx.Header("content-type", "application/json")

	pair := ctx.URLParam("coin_pair")
	selectType := ctx.URLParam("type")
	flag := ctx.URLParam("flag")

	if pair == "" || selectType == "" || flag == "" || (flag != "all" && flag != "last") {
		ctx.JSON(common.KlineError("parameter error"))
		return
	}

	var ts string
	ts, ok := selectTypes[selectType]
	if !ok {
		ctx.JSON(common.KlineError("parameter error"))
		return
	}

	conn := core.BK.Redis.OTEPool.Get()
	defer conn.Close()

	var key string
	if flag == "all" {
		key = function.GetKlineCacheDataKey(pair)
	} else {
		key = function.GetKlineCacheLastKey(pair)
	}

	var lines interface{}
	lines = make([]ResultItem, 0)

	data, err := redis.String(conn.Do("HGET", key, ts))
	if err != nil {
		log.Errorf("get kline data error, msg: %s", err)
		ctx.JSON(common.KlineSuccess(lines))
		return
	}

	if flag == "all" {
		var values []ResultItem
		err = json.Unmarshal([]byte(data), &values)
		if err != nil {
			log.Errorf("json unmarshal data error, msg: %s", err.Error())
			ctx.JSON(common.KlineSuccess(lines))
			return
		}
		lines = values
	} else {
		var value ResultItem
		err = json.Unmarshal([]byte(data), &value)
		if err != nil {
			log.Errorf("json unmarshal data error, msg: %s", err.Error())
			ctx.JSON(common.KlineSuccess(lines))
			return
		}
		lines = []ResultItem{value}
	}

	ctx.JSON(common.KlineSuccess(lines))

}
